package 并发编程07.ForkJoin累加案例;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * 作者：idea
 * 日期：2018/8/19
 * 描述：
 */
public class CountTaskTmp extends RecursiveTask<Integer>{

    private static final int THRESHOLD=2;

    private int start;

    private int end;

    public CountTaskTmp(int start,int end){
        this.start=start;
        this.end=end;
    }


    @Override
    protected Integer compute() {
        int sum=0;
        boolean canCount=(end-start)<=THRESHOLD;
        if(canCount){
            for(int i=start;i<=end;i++){
                sum+=i;
            }
        }else{
            int mid=(start+end)/2;
            CountTaskTmp leftTask=new CountTaskTmp(start,mid);
            CountTaskTmp rightTask=new CountTaskTmp(mid+1,end);
            //执行子任务
            leftTask.fork();
            rightTask.fork();
            int rightResult=rightTask.join();
            int leftResult=leftTask.join();

            sum=rightResult+leftResult;
        }
        return sum;
    }


    public static void main(String[] args) {
        ForkJoinPool forkJoinPool=new ForkJoinPool();
        CountTaskTmp taskTmp=new CountTaskTmp(1,10);
        Future<Integer> result=forkJoinPool.submit(taskTmp);
        System.out.println("开始计算");
        try {
            System.out.println(result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }


}
